import prompt from "@system.prompt"

var refreshHeaderComponent;
var contentComponent;
var TAG = "refreshLoadMoreComponent----"
var count = 0
var touch, moved, startY, diff, moveDiff = 60, pagePull = true;
var loadData = false;

var refreshing = "refreshing"
var refreshDrag = "refreshDrag"
var refreshDragRelease = "refreshDragRelease"

export default {
    data() {
        return {
            headerHeight: "0px",
            refreshDefaultText: "下拉刷新",
            isShowLoadMore: "visible",
            isShowDefaultHeader: true,
            isShowDefaultContent: true,
            isShowDefaultFooter: true,
            isShowLoadMoreView:true,
        }
    },
    props: {
        headerMoveOffset: {
            default: moveDiff,
        }
    },
    onInit() {
        console.log(TAG + "onInit")
    },
    onAttached() {
        refreshHeaderComponent = this.$element("header")
        contentComponent = this.$element("content")
        this.isShowDefaultHeader = !checkHasSlot(this.$element("header"), "header")
        this.isShowDefaultContent = !checkHasSlot(this.$element("content"), "content")
        this.isShowDefaultFooter = !checkHasSlot(this.$element("footer"), "footer")
        moveDiff = this.isShowDefaultHeader ? moveDiff : this.headerMoveOffset
    },
    onContentMove(e) {
        console.log(TAG + "onContentMove")
        if (!touch || !pagePull) {
            return;
        }
        var touchesDiff = e.touches[0].localY - startY; //计算的移动位移
        if (touchesDiff < 0) {
            //说明页面是向上滑的，不做任何操作
            moved = false;
            return;
        }
        moved = true;
        diff = touchesDiff;
        var distance = 0;
        if (diff <= moveDiff) {
            //moveDiff至少要等于loading的高度
            //当滑动小于规定的临界值时
            distance = diff;
            onRefreshState(this, refreshDrag)
        } else {
            onRefreshState(this, refreshDragRelease)
            // 弹性
            if (touchesDiff <= (2 * moveDiff)) {
                distance = moveDiff + 0.5 * (touchesDiff - moveDiff);
            } else {
                distance = moveDiff + 0.1 * (touchesDiff - moveDiff) + 0.05 * (touchesDiff - 2 * moveDiff);
            }
        }
        if (distance > 0) {
            //滑动的距离
            this.headerHeight = distance + 'px';
        }
    },
    onContentStart(e) {
        var rootTop = this.$element().getBoundingClientRect().top;
        console.log(TAG + "onContentStart RootTop:" + rootTop)
        console.log(TAG + "onContentStart top:" + contentComponent.getBoundingClientRect().top)
        if (contentComponent.getBoundingClientRect().top > rootTop) {
            //当页面已经有滚动或者不是置顶的时候，不需要进行下拉刷新，是页面正常的滑动
            touch = false;
            return;
        }
        touch = true; //触摸开始
        moved = false; //还没有进行下拉刷新的滑动
        startY = e.touches[0].localY; //记录当前手指在屏幕上的纵向坐标，用于判断页面是上滑还是下滑
    },
    onTouch() {
        console.log(TAG + "onTouch")
        if (!touch || !moved) {
            return;
        }
        var that = this;
        pagePull = false;
        if (diff > moveDiff) {
            // 下拉时-超过可显示区域时
            onRefreshState(this, refreshing)
            this.headerHeight = moveDiff + 'px';
            doRefreshInBackground(this).then(() => {
                this.css(refreshHeaderComponent, moveDiff, 0, () => {
                    that.headerHeight = '0px';
                });
                //控制在刷新期间，重复向下拉动，不做任何操作
                pagePull = true;
            });
        } else {
            // 下拉时-未超过可显示区域时
            pagePull = true;
            this.css(refreshHeaderComponent, diff, 0, () => {
                that.headerHeight = '0px';
            });
        }
    },
    css(component, start, end, callBack) {
        var options = {
            duration: 500,
            fill: 'both',
        };
        var frames = [
            {
                height: start + "px"
            }, {
                height: end + "px"
            },
        ];
        var animation = component.animate(frames, options);
        animation.onfinish = callBack;
        animation.play();
    },
    onReachBottom() {
//        prompt.showToast({
//            message: "onReachBottom"
//        });
        //当数据正在加载时，直接返回
        if (loadData) {
            return
        }
        this.isShowLoadMore = "visible"
        loadData = true;
        doLoadMoreInBackground(this).then(() => {
            count++
            loadData = false;
            this.isShowLoadMore = "hidden"
        })
    },
    onReachTop() {
        count = 0
//        prompt.showToast({
//            message: "onReachTop"
//        });
    },
    isShowLoadMoreViewFunc(isShow) {
        this.isShowLoadMoreView = isShow
    }
}

/**
 * 下拉刷新状态
 * @param that 上下文
 * @param state 刷新状态
 */
function onRefreshState(that, state) {
    console.log(TAG + " onRefreshState state : " + state)
    if (state === refreshing) {
        // refreshing
        that.refreshDefaultText = '刷新中';
    } else if (state === refreshDrag) {
        // refreshDrag
        that.refreshDefaultText = '下拉可刷新';
    } else {
        // refreshDragRelease
        that.refreshDefaultText = '释放可刷新';
    }
    that.$emit('refreshState', { state: state });
}

/**
 * 执行上拉加载更多操作
 */
async function doLoadMoreInBackground(that) {
    return await  new Promise((resolve, reject) => {
        that.$emit('loadMore', { resolveFunc: resolve, rejectFunc: reject });
    })
}

/**
 * 执行刷新动作
 */
async function doRefreshInBackground(that) {
    return await  new Promise((resolve, reject) => {
        that.$emit('refresh', { resolveFunc: resolve, rejectFunc: reject });
    })
}

/**
 *
* 判断是否有对应插槽
* @param root 根布局
* @param type 插槽名称
* @return true->插槽已添加，false->插槽未添加
 */
function checkHasSlot(root, type) {
    var array = root.pureChildren;
    for (var child of  array) {
        if (child.attr.slot == type) {
            return true
        }
    }
    return false
}